<?php

namespace App\Http\Middleware;

use App\Models\SmsLog;
use Carbon\Carbon;

/**
 * 财务后台接口验证操作短信
 * Class ValidateFinanceOperationSmsCaptcha
 * @package App\Http\Middleware
 */
class ValidateFinanceOperationSmsCaptcha
{
    public function handle($request, \Closure $next)
    {
        try {
            $smsLog = SmsLog::query()
                ->where('phone', \Auth::user()['phone'])
                ->orderBy('created_at', 'desc')
                ->firstOrFail()
                ->toArray();
        } catch (\Throwable $e) {
            abort(400, '验证码错误或已失效');
        }
        if (!((int) $smsLog['properties']['code'] === (int) $request->get('sms_captcha')
            && Carbon::now()->isBefore(Carbon::parse($smsLog['properties']['expired_at'])))) {

            abort(400, '验证码错误或已失效');
        }

        return $next($request);
    }
}
